package com.dqy.twserver.server.handle;

import com.dqy.twserver.server.codec.DataEncode;
import com.dqy.twserver.server.dto.GameDto;
import com.dqy.twserver.server.handle.ehandle.GameEventHandle;
import com.dqy.twserver.server.support.Constans;
import com.dqy.twserver.server.support.MsgPush;
import com.dqy.twserver.server.support.Player;
import com.dqy.twserver.server.support.SupportMap;
import com.dqy.twserver.server.support.data.RoomInfo;
import com.google.gson.GsonBuilder;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.nio.channels.SocketChannel;
import java.util.Map;

//数据入站处理器
public class ServerInboundHandle extends SimpleChannelInboundHandler<GameDto> {
    static Logger logger = LoggerFactory.getLogger(ServerInboundHandle.class);


    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, GameDto gameDto) throws Exception {
        logger.info("新的客户端请求到来,eventType={}",gameDto.getEventType());
        GameEventHandle handle = SupportMap.gameEventHandleMap.get(gameDto.getEventType());
        NioSocketChannel channel = (NioSocketChannel) channelHandlerContext.channel();
        try {
            handle.handle(gameDto, channel);
        }catch (Exception e){
            logger.info("服务端异常,原因{}",e);
            GameDto err=new GameDto();
            err.setInfo("服务端异常");
            err.setSts(500);
            channel.writeAndFlush(err);
        }
    }

    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        logger.info("新的客户端连接到来...");
        NioSocketChannel channel = (NioSocketChannel) ctx.channel();
        InetSocketAddress inetSocketAddress = channel.remoteAddress();
        logger.info("客户端地址:{}:{}",inetSocketAddress.getHostString(),inetSocketAddress.getPort());
        logger.info("客户端请求处理完毕...");
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        String cid = ctx.channel().id().toString();
        SupportMap.gameEventHandleMap.get(Constans.EVENT_TYPE_UNREGISTER_HOOK).handle(null, (NioSocketChannel) ctx.channel());
    }
}
